#!/usr/bin/python
import sys
import pexpect
import getpass, os
import re
import time
import logging

LOGFILE = '/home/bsmp/work/log/stormssh.log'

#Logger
logging.basicConfig(level=logging.DEBUG,  
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',  
                    datefmt='%Y-%m-%d %H:%M:%S',  
                    filename=LOGFILE,  
                    filemode='w')  
console = logging.StreamHandler()  
console.setLevel(logging.DEBUG)  
# set print format
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')  
console.setFormatter(formatter)  
#
logging.getLogger('').addHandler(console)  
logger1 = logging.getLogger('test.delay')    


#putfile = '/home/B002/appproto_lib/appproto.etxt'
#dstdir = '/home/bsmp/dpi_flow_parser_v1.01/config/'

HOSTLIST = '/home/bsmp/work/config/hostnames.txt'

def ssh_command (user, host, password, command):
    ssh_newkey = 'Are you sure you want to continue connecting'
    child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command))
    i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'password: '])
    if i == 0:
        #print 'ERROR!'
        #print 'SSH could not login. Here is what SSH said:'
        #print child.before, child.after
        return None
    if i == 1:
        child.sendline ('yes')
        child.expect ('password: ')
        i = child.expect([pexpect.TIMEOUT, 'password: '])
        if i == 0:
        	#print 'ERROR!'
        	#print 'SSH could not login. Here is what SSH said:'
        	#print child.before, child.after
        	return None
    child.sendline(password)
    return child

def scp_command(ip, user, passwd, dst_path, filename):  
    passwd_key = '.*assword.*'  
    if os.path.isdir(filename):   
        cmdline = 'scp -r %s %s@%s:%s' % (filename, user, ip, dst_path)   
    else:   
        cmdline = 'scp %s %s@%s:%s' % (filename, user, ip, dst_path)   
    try:  
        child = pexpect.spawn(cmdline)  
        child.expect(passwd_key)  
        child.sendline(passwd)  
        child.expect(pexpect.EOF)  
        logger.debug( '%s uploading success.'%(ip) )   
        print '%s uploading success.'%(ip)
    except:  
        logger.debug( '%s uploading failed.'%(ip) )
        print '%s uploading success.'%(ip)  

def main ():

    user=sys.argv[1]
    passwd=sys.argv[2]
    destpath=sys.argv[3]
    filename=sys.argv[4]
    
    logger.debug('scp starting ...')
    
#    f = os.open(HOSTLIST, "r")  
#    while True:  
#        hostname = f.readline()  
#        if line:  
#            scp_command(hostname, user, passwd, destpath, filename)
#        else:  
#            break
#    f.close()  
    
    
	
    #ltime = time.time()
    #ftime = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
    #bak_name = putfile + '_' + ftime
    #os.rename(putfile, bak_name)

    logger.debug('scp end ...')
    return

if __name__ == '__main__':
    # do the UNIX double-fork magic, see Stevens' "Advanced 
    # Programming in the UNIX Environment" for details (ISBN 0201563177)
    # decouple from parent environment
    #os.chdir("/home/B002/appproto_lib") 
    # start the daemon main loop
    try:
        main()
    except Exception, e:
        print str(e)
        #traceback.print_exc()
        os._exit(1)
